<template>
  <div class="owner-list-container">
    <!-- 搜索和操作区域 -->
    <el-card class="search-card" shadow="hover">
      <template #header>
        <div class="card-header">
          <div class="header-title">
            <el-icon><User /></el-icon>
            <span>业主管理</span>
          </div>
          <div class="header-operations">
            <el-button type="primary" @click="handleAdd" plain>
              <el-icon><Plus /></el-icon>添加业主
            </el-button>
            <el-button type="danger" @click="handleBatchDelete" :disabled="multipleSelection.length === 0" plain>
              <el-icon><Delete /></el-icon>批量删除
            </el-button>
            <el-button type="success" @click="handleExport" plain>
              <el-icon><Download /></el-icon>导出Excel
            </el-button>
            <el-button type="warning" @click="handleImport" plain>
              <el-icon><Upload /></el-icon>导入Excel
            </el-button>
          </div>
        </div>
      </template>
      
      <div class="illustration-container">
        <img src="https://img.icons8.com/color/96/000000/family.png" alt="Owner Management Illustration" class="illustration-image">
        <div class="illustration-text">
          <h3>业主信息管理</h3>
          <p>高效管理小区业主信息，维护良好的社区关系</p>
        </div>
      </div>
      
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="业主姓名">
          <el-input v-model="searchForm.name" placeholder="请输入业主姓名" clearable>
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item label="联系电话">
          <el-input v-model="searchForm.phoneNumber" placeholder="请输入联系电话" clearable>
            <template #prefix>
              <el-icon><Phone /></el-icon>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item label="所属小区">
          <el-select v-model="searchForm.communityId" placeholder="选择小区" clearable>
            <el-option
              v-for="item in communities"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            >
              <div class="community-option">
                <el-icon><House /></el-icon>
                <span>{{ item.name }}</span>
              </div>
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onSearch">查询</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 表格区域 -->
    <el-card class="table-card" shadow="hover">
      <template #header>
        <div class="card-header">
          <span>业主列表</span>
          <el-tag type="info">共 {{ total }} 条记录</el-tag>
        </div>
      </template>

      <el-table
        v-loading="loading"
        :data="tableData"
        style="width: 100%"
        @selection-change="handleSelectionChange"
        stripe
        border
        highlight-current-row
        :header-cell-style="{ background: '#f5f7fa', color: '#606266' }"
        :empty-text="'暂无业主数据'"
      >
        <el-table-column type="selection" width="55" fixed="left" />
        <el-table-column prop="name" label="业主姓名" width="120" fixed="left">
          <template #default="scope">
            <div class="cell-with-icon">
              <el-icon><User /></el-icon>
              <span>{{ scope.row.name }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="communityName" label="所属小区" width="120" fixed="left">
          <template #default="scope">
            <div class="cell-with-icon">
              <el-icon><House /></el-icon>
              <span>{{ scope.row.communityName || '未绑定' }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="homes" label="所属房产" width="200" fixed="left">
          <template #default="scope">
            <el-tooltip 
              v-if="scope.row.homes && scope.row.homes.length > 0"
              :content="getHomeDetails(scope.row.homes)" 
              placement="top" 
              :show-after="500"
              width="250"
              effect="light"
            >
              <div class="cell-with-icon home-info">
                <el-icon><HomeFilled /></el-icon>
                <span>{{ formatHomes(scope.row.homes) }}</span>
                <el-badge 
                  v-if="scope.row.homes && scope.row.homes.length > 1" 
                  :value="scope.row.homes.length"
                  type="primary"
                  class="home-count"
                ></el-badge>
              </div>
            </el-tooltip>
            <span v-else>未绑定房产</span>
          </template>
        </el-table-column>
        <el-table-column prop="gender" label="性别" width="80">
          <template #default="scope">
            <el-tag 
              :type="scope.row.gender === '男' ? 'primary' : 'danger'" 
              effect="plain"
              size="small"
            >
              {{ scope.row.gender }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="phoneNumber" label="联系电话" width="150">
          <template #default="scope">
            <div class="cell-with-icon">
              <el-icon><Phone /></el-icon>
              <span>{{ scope.row.phoneNumber }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="idCard" label="身份证号" width="200">
          <template #default="scope">
            <div class="cell-with-icon">
              <el-icon><Document /></el-icon>
              <span>{{ scope.row.idCard }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="profession" label="职业" width="120" />
        <el-table-column prop="email" label="邮箱" width="180">
          <template #default="scope">
            <div class="cell-with-icon">
              <el-icon><Message /></el-icon>
              <span>{{ scope.row.email }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="remarks" label="备注" width="200">
          <template #default="scope">
            <el-tooltip :content="scope.row.remarks" placement="top" :show-after="500">
              <div class="description-cell">
                <el-icon><ChatDotRound /></el-icon>
                <span>{{ scope.row.remarks || '暂无备注' }}</span>
              </div>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column prop="createdAt" label="创建时间" width="180">
          <template #default="scope">
            <div class="cell-with-icon">
              <el-icon><Calendar /></el-icon>
              {{ formatDate(scope.row.createdAt) }}
            </div>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180" fixed="right">
          <template #default="scope">
            <el-button size="small" @click="handleEdit(scope.row)" type="primary" text>
              <el-icon><Edit /></el-icon>编辑
            </el-button>
            <el-button size="small" @click="handleDelete(scope.row)" type="danger" text>
              <el-icon><Delete /></el-icon>删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination-box" v-if="total > 0">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 30, 50]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          background
        />
      </div>
    </el-card>

    <!-- 导入Excel对话框 -->
    <el-dialog v-model="importDialogVisible" title="导入Excel" width="500px">
      <div class="import-dialog-content">
        <el-alert
          title="请先下载模板，按照模板格式填写数据后上传"
          type="info"
          :closable="false"
          style="margin-bottom: 20px;"
        />
        
        <div class="template-download">
          <el-button type="primary" @click="downloadTemplate" size="small">
            <el-icon><Download /></el-icon>下载模板
          </el-button>
        </div>
        
        <el-upload
          class="excel-upload"
          action="#"
          :auto-upload="false"
          :on-change="handleFileChange"
          :file-list="fileList"
          :limit="1"
          accept=".xlsx,.xls"
        >
          <el-button type="primary">选择文件</el-button>
          <template #tip>
            <div class="el-upload__tip">只能上传xlsx/xls文件</div>
          </template>
        </el-upload>
      </div>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="importDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitImport" :loading="importing">
            导入
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { 
  Plus, 
  Edit, 
  Delete, 
  Search, 
  User, 
  Phone, 
  Document, 
  Message, 
  Calendar,
  ChatDotRound,
  House,
  HomeFilled,
  Download,
  Upload
} from '@element-plus/icons-vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import axios from 'axios';
import ExcelUtil from '@/utils/ExcelUtil';

export default {
  name: 'OwnerList',
  components: {
    Plus,
    Edit,
    Delete,
    Search,
    User,
    Phone,
    Document,
    Message,
    Calendar,
    ChatDotRound,
    House,
    HomeFilled,
    Download,
    Upload
  },
  data() {
    return {
      searchForm: {
        name: '',
        phoneNumber: '',
        communityId: ''
      },
      tableData: [],
      multipleSelection: [],
      currentPage: 1,
      pageSize: 10,
      total: 0,
      loading: false,
      communities: [],
      importDialogVisible: false,
      fileList: [],
      importing: false,
      exportLoading: false
    };
  },
  created() {
    this.fetchOwners();
    this.fetchCommunities();
  },
  methods: {
    // 格式化日期
    formatDate(dateString) {
      if (!dateString) return '';
      const date = new Date(dateString);
      return date.toLocaleString();
    },

    // 格式化房产信息
    formatHomes(homes) {
      if (!homes || homes.length === 0) return '未绑定';
      
      // 如果只有一套房产，直接返回详细信息
      if (homes.length === 1) {
        const home = homes[0];
        const buildingName = home.buildingName || '';
        const homeName = home.name || '';
        const area = home.area ? `${home.area}㎡` : '';
        return `${buildingName}栋 ${homeName} ${area}`;
      }
      
      // 如果有多套房产，返回数量和简要信息
      return `${homes.length}套房产`;
    },
    
    // 获取房产详细信息（用于悬浮提示）
    getHomeDetails(homes) {
      if (!homes || homes.length === 0) return '未绑定房产';
      
      return homes.map(home => {
        const buildingName = home.buildingName || '';
        const homeName = home.name || '';
        const area = home.area ? `${home.area}㎡` : '';
        const type = home.type ? `类型：${home.type}` : '';
        const direction = home.direction ? `朝向：${home.direction}` : '';
        
        return `${buildingName}栋 ${homeName} ${area} ${type} ${direction}`.trim();
      }).join('\n');
    },

    // 获取业主列表
    async fetchOwners() {
      try {
        this.loading = true;
        const response = await axios.get('/api/owners', {
          params: {
            page: this.currentPage - 1,
            size: this.pageSize
          }
        });
        console.log('业主列表API响应:', response.data); // 添加调试日志
        
        // 更新处理响应数据的逻辑
        if (response.data && response.data.content) {
          // 分页响应格式
          this.tableData = response.data.content;
          this.total = response.data.totalItems || response.data.totalElements;
        } else if (Array.isArray(response.data)) {
          // 数组响应格式
          this.tableData = response.data;
          this.total = response.data.length;
        } else {
          // 其他情况
          this.tableData = [];
          this.total = 0;
        }
        console.log('设置的total值:', this.total); // 添加调试日志
      } catch (error) {
        console.error('Failed to fetch owners:', error);
        ElMessage.error('获取业主列表失败');
        this.tableData = [];
        this.total = 0;
      } finally {
        this.loading = false;
      }
    },

    // 搜索业主
    async onSearch() {
      try {
        this.loading = true;
        let url = '/api/owners';
        let params = {
          page: this.currentPage - 1,
          size: this.pageSize
        };
        
        if (this.searchForm.name) {
          params.name = this.searchForm.name;
        }
        
        if (this.searchForm.phoneNumber) {
          params.phoneNumber = this.searchForm.phoneNumber;
        }
        
        if (this.searchForm.communityId) {
          params.communityId = this.searchForm.communityId;
        }
        
        const response = await axios.get(url, { params });
        console.log('业主搜索API响应:', response.data); // 添加调试日志
        
        // 更新处理响应数据的逻辑
        if (response.data && response.data.content) {
          // 分页响应格式
          this.tableData = response.data.content;
          this.total = response.data.totalItems || response.data.totalElements;
        } else if (Array.isArray(response.data)) {
          // 数组响应格式
          this.tableData = response.data;
          this.total = response.data.length;
        } else {
          // 其他情况
          this.tableData = [];
          this.total = 0;
        }
        console.log('搜索后设置的total值:', this.total); // 添加调试日志
      } catch (error) {
        console.error('Search failed:', error);
        ElMessage.error('搜索失败');
        this.tableData = [];
        this.total = 0;
      } finally {
        this.loading = false;
      }
    },

    resetSearch() {
      this.searchForm.name = '';
      this.searchForm.phoneNumber = '';
      this.searchForm.communityId = '';
      this.currentPage = 1; // 重置为第一页
      this.fetchOwners();
    },

    handleAdd() {
      this.$router.push('/property/personnel/owner/add');
    },

    handleEdit(row) {
      this.$router.push({
        path: '/property/personnel/owner/add',
        query: { id: row.id }
      });
    },

    async handleDelete(row) {
      try {
        await ElMessageBox.confirm(`确认要删除业主 ${row.name} 吗？`, '警告', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        });
        
        // 如果用户确认，执行删除
        const response = await axios.delete(`/api/owners/${row.id}`);
        console.log('删除响应:', response);
        ElMessage.success('删除成功');
        // 刷新列表
        this.fetchOwners();
      } catch (error) {
        // 用户取消操作不显示错误提示
        if (error === 'cancel' || error.toString().includes('cancel')) {
          ElMessage.info('已取消删除');
          return;
        }
        
        // 打印详细错误信息以便调试
        console.error('删除失败详细信息:', error);
        if (error.response) {
          console.error('响应状态:', error.response.status);
          console.error('响应数据:', error.response.data);
        }
        
        ElMessage.error('删除失败，请稍后重试');
      }
    },

    async handleBatchDelete() {
      if (this.multipleSelection.length === 0) {
        ElMessage.warning('请至少选择一条记录');
        return;
      }

      try {
        await ElMessageBox.confirm(`确认要删除选中的 ${this.multipleSelection.length} 条记录吗？`, '警告', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        });
        
        // 收集所有要删除的ID
        const ids = this.multipleSelection.map(item => item.id);
        
        try {
          // 使用批量删除接口
          await axios.delete('/api/owners/batch', {
            data: ids
          });
        } catch (error) {
          // 如果批量删除接口不可用，则使用单个删除接口
          const deleteRequests = ids.map(id => axios.delete(`/api/owners/${id}`));
          await Promise.all(deleteRequests);
        }
        
        ElMessage.success('批量删除成功');
        this.fetchOwners();
      } catch (error) {
        // 用户取消操作不显示错误提示
        if (error === 'cancel' || error.toString().includes('cancel')) {
          ElMessage.info('已取消删除');
          return;
        }
        
        // 打印详细错误信息以便调试
        console.error('批量删除失败详细信息:', error);
        if (error.response) {
          console.error('响应状态:', error.response.status);
          console.error('响应数据:', error.response.data);
        }
        
        ElMessage.error('批量删除失败，请稍后重试');
      }
    },

    handleSelectionChange(val) {
      this.multipleSelection = val;
    },

    handleSizeChange(val) {
      this.pageSize = val;
      this.fetchOwners();
    },

    handleCurrentChange(val) {
      this.currentPage = val;
      this.fetchOwners();
    },

    async fetchCommunities() {
      try {
        const response = await axios.get('/api/communities');
        this.communities = response.data;
      } catch (error) {
        console.error('Failed to fetch communities:', error);
        ElMessage.error('获取小区列表失败');
        this.communities = [];
      }
    },

    handleImport() {
      this.importDialogVisible = true;
      this.fileList = [];
    },

    async downloadTemplate() {
      try {
        const response = await axios.get('/api/owners/template', {
          responseType: 'blob'
        });
        
        const blob = new Blob([response.data], {
          type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
        });
        
        const link = document.createElement('a');
        link.href = URL.createObjectURL(blob);
        link.download = '业主信息导入模板.xlsx';
        link.click();
        URL.revokeObjectURL(link.href);
      } catch (error) {
        console.error('下载模板失败:', error);
        ElMessage.error('下载模板失败: ' + (error.message || '未知错误'));
      }
    },

    handleFileChange(file) {
      this.fileList = [file];
    },

    async submitImport() {
      if (!this.fileList.length) {
        ElMessage.warning('请选择要导入的Excel文件');
        return;
      }
      
      try {
        this.importing = true;
        
        const formData = new FormData();
        formData.append('file', this.fileList[0].raw);
        
        const response = await axios.post('/api/owners/import', formData, {
          headers: {
            'Content-Type': 'multipart/form-data'
          }
        });
        
        ElMessage.success(`导入成功，成功导入${response.data.successCount}条数据`);
        this.importDialogVisible = false;
        this.fetchOwners();
      } catch (error) {
        console.error('导入失败:', error);
        ElMessage.error('导入失败: ' + (error.response?.data?.message || error.message || '未知错误'));
      } finally {
        this.importing = false;
      }
    },

    // 导出Excel
    async handleExport() {
      try {
        this.exportLoading = true;
        
        // 定义表头
        const header = [
          { label: '姓名', prop: 'name' },
          { label: '性别', prop: 'gender' },
          { label: '电话号码', prop: 'phoneNumber' },
          { label: '身份证号', prop: 'idCard' },
          { label: '职业', prop: 'profession' },
          { label: '邮箱', prop: 'email' },
          { label: '备注', prop: 'remarks' }
        ];
        
        // 获取所有数据
        const response = await axios.get('/api/owners/all');
        const data = response.data;
        
        // 导出Excel
        ExcelUtil.exportExcel(data, '业主信息表', header);
        
        ElMessage.success('导出成功');
      } catch (error) {
        console.error('导出失败:', error);
        ElMessage.error('导出失败: ' + (error.message || '未知错误'));
      } finally {
        this.exportLoading = false;
      }
    }
  }
};
</script>

<style scoped>
.owner-list-container {
  padding: 10px;
}

/* 搜索卡片样式 */
.search-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 18px;
  font-weight: 600;
}

.header-title {
  display: flex;
  align-items: center;
}

.header-title .el-icon {
  font-size: 22px;
  margin-right: 8px;
  color: #409EFF;
}

.header-operations {
  display: flex;
  gap: 10px;
}

.header-operations :deep(.el-button) {
  font-size: 16px;
  height: 42px;
  padding: 8px 16px;
}

.header-operations :deep(.el-icon) {
  font-size: 18px;
  margin-right: 5px;
}

/* 插图容器样式 */
.illustration-container {
  display: flex;
  align-items: center;
  background-color: #f0f9ff;
  border-radius: 8px;
  padding: 15px;
  margin-bottom: 20px;
}

.illustration-image {
  width: 80px;
  height: 80px;
  margin-right: 20px;
}

.illustration-text h3 {
  font-size: 20px;
  color: #409EFF;
  margin: 0 0 8px 0;
}

.illustration-text p {
  font-size: 16px;
  color: #606266;
  margin: 0;
}

.search-form {
  display: flex;
  align-items: center;
}

.search-form :deep(.el-form-item__label) {
  font-size: 16px;
}

.search-form :deep(.el-input__inner) {
  font-size: 16px;
  height: 42px;
}

.search-form :deep(.el-button) {
  font-size: 16px;
  height: 42px;
  padding: 10px 20px;
}

/* 表格卡片样式 */
.table-card {
  margin-bottom: 20px;
}

.table-card :deep(.el-table) {
  font-size: 16px;
}

.table-card :deep(.el-table th) {
  font-size: 16px;
  padding: 12px 0;
}

.table-card :deep(.el-table td) {
  padding: 12px 0;
}

.cell-with-icon {
  display: flex;
  align-items: center;
  font-size: 16px;
}

.cell-with-icon .el-icon {
  margin-right: 5px;
  font-size: 18px;
}

/* 房产信息样式 */
.home-info {
  cursor: pointer;
  display: flex;
  align-items: center;
  position: relative;
  padding-right: 30px;
}

.home-info .el-icon {
  color: #67c23a;
}

.home-count {
  margin-left: 5px;
  position: absolute;
  right: 0;
  top: 0;
}

/* 小区选择器样式 */
.community-option {
  display: flex;
  align-items: center;
  font-size: 14px;
}

.community-option .el-icon {
  margin-right: 5px;
  color: #409EFF;
}

.description-cell {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  max-width: 180px;
  display: flex;
  align-items: center;
}

.description-cell .el-icon {
  margin-right: 5px;
  font-size: 18px;
  color: #909399;
}

/* 分页样式 */
.pagination-box {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.pagination-box :deep(.el-pagination) {
  font-size: 16px;
}

.pagination-box :deep(.el-pagination .el-input__inner) {
  font-size: 16px;
  height: 36px;
}

.pagination-box :deep(.el-pagination button) {
  font-size: 16px;
  min-width: 36px;
  height: 36px;
}

/* 按钮样式调整 */
:deep(.el-button--text) {
  font-size: 16px;
}

:deep(.el-button) {
  font-size: 16px;
}

:deep(.el-tag) {
  font-size: 14px;
  padding: 2px 8px;
}

/* 响应式调整 */
@media screen and (max-width: 768px) {
  .search-form {
    flex-direction: column;
    align-items: stretch;
  }
  
  .search-form .el-form-item {
    margin-right: 0;
    margin-bottom: 15px;
  }
  
  .illustration-container {
    flex-direction: column;
    text-align: center;
  }
  
  .illustration-image {
    margin-right: 0;
    margin-bottom: 15px;
  }
}

/* 导入导出相关样式 */
.import-dialog-content {
  padding: 10px 0;
}

.template-download {
  margin-bottom: 20px;
  text-align: center;
}

.excel-upload {
  text-align: center;
}

.el-upload__tip {
  margin-top: 10px;
  font-size: 14px;
  color: #909399;
}
</style>
